package com.yanchangapp.ui.activity.mail;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.yanchangapp.R;
import com.yanchangapp.base.MyApi;
import com.yanchangapp.model.bean.NotifyBean;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.ui.activity.base.LoginActivity;
import com.zxl.baselib.baseapp.AppManager;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.ui.base.BaseObserver;
import com.zxl.baselib.ui.base.BasePresenter;
import com.zxl.baselib.ui.base.ExceptionHandle;
import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/**
 * Android加载WebView界面效果...
 */
public class WebViewActivity extends BaseActivity {

    @BindView(R.id.webView)
    WebView mWebView;
    @BindView(R.id.frameProgress)
    RelativeLayout frameProgress;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    public static final String INTENT_URL = "intent_url";
    private String innerUrl;
    private static final String TAG = "WebViewActivity";
    private boolean isFirstLoading = true;
    private boolean isError;
    private boolean isSuccess;

    public static void show(Activity mActivity, String url) {
        Intent intent = new Intent(mActivity, WebViewActivity.class);
        intent.putExtra(INTENT_URL, url);
        mActivity.startActivity(intent);
    }

    public static void show(Activity mActivity) {
        Intent intent = new Intent(mActivity, WebViewActivity.class);
        mActivity.startActivity(intent);
    }

    @Override
    protected void init() {
        if (getIntent() != null) {
            innerUrl = getIntent().getStringExtra(INTENT_URL);
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_web_view;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        showLoading();
        initWebView();
        loadWevView();
    }


    private void showContent(){
        if (frameProgress.getVisibility() == View.VISIBLE){
            frameProgress.setVisibility(View.GONE);
        }

        if (mWebView.getVisibility() == View.GONE){
            mWebView.setVisibility(View.VISIBLE);
        }

        if (llErrorNetwork.getVisibility() == View.VISIBLE){
            llErrorNetwork.setVisibility(View.GONE);
        }
    }

    private void showErr(){
        if (frameProgress.getVisibility() == View.VISIBLE){
            frameProgress.setVisibility(View.GONE);
        }

        if (mWebView.getVisibility() == View.VISIBLE){
            mWebView.setVisibility(View.GONE);
        }

        if (llErrorNetwork.getVisibility() == View.GONE){
            llErrorNetwork.setVisibility(View.VISIBLE);
        }
    }

    private void showLoading(){
        if (frameProgress.getVisibility() == View.GONE){
            frameProgress.setVisibility(View.VISIBLE);
        }

        if (mWebView.getVisibility() == View.VISIBLE){
            mWebView.setVisibility(View.GONE);
        }

        if (llErrorNetwork.getVisibility() == View.VISIBLE){
            llErrorNetwork.setVisibility(View.GONE);
        }
    }


    private void initWebView() {
        WebSettings setting = mWebView.getSettings();
        /**支持Js**/
        setting.setJavaScriptEnabled(true);
        /**设置自适应屏幕，两者合用**/
        //将图片调整到适合webview的大小
        setting.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        setting.setLoadWithOverviewMode(true);
        /**缩放操作**/
        // 是否支持画面缩放，默认不支持
        setting.setBuiltInZoomControls(false);
        setting.setSupportZoom(false);
        // 是否显示缩放图标，默认显示
        setting.setDisplayZoomControls(false);
        // 设置网页内容自适应屏幕大小
        /**设置允许JS弹窗**/
        setting.setJavaScriptCanOpenWindowsAutomatically(true);
        setting.setAppCacheEnabled(true);
        setting.setDomStorageEnabled(true);
        setting.setGeolocationEnabled(true);
        setting.setAppCacheMaxSize(Long.MAX_VALUE);
        setting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        /*关闭webview中缓存*/
        setting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        /*设置可以访问文件*/
        setting.setAllowFileAccess(true);
        setting.setAllowFileAccessFromFileURLs(true);
        setting.setAllowUniversalAccessFromFileURLs(true);
        setting.setAllowContentAccess(true);
        setting.setBlockNetworkImage(true);
        // 设置事件监听
        mWebView.addJavascriptInterface(new JSInterface(), "bridge");
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                mWebView.getSettings().setBlockNetworkImage(true);
                if (isFirstLoading){
                    isError = false;
                    showLoading();
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view,url);
                mWebView.getSettings().setBlockNetworkImage(false);
                if (!isFirstLoading){
                    return;
                }
                if (!isError) {
                    isSuccess = true;
                    showContent();
                    isError = false;
                    if (isFirstLoading){
                        isFirstLoading = false;
                    }
                    return;
                }
                // 失败的处理
                showErr();
                isError = false;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                isError = true;
                isSuccess = false;
            }
        });
    }


    /**
     * 设置处理 -- 方法处理
     * <p>
     * JS调用原生...
     */
    private final class JSInterface {
        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        public void event(final String info) {
            // 获得传递的值
            Gson gson = new Gson();
            NotifyBean notifyBean = gson.fromJson(info, NotifyBean.class);
            String command = notifyBean.command;
            if ("back".equals(command)) {
                finish();
            } else if ("logout".equals(command)) {
                doLogout();
            }
        }
    }

    public void doLogout() {
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            UserCache.clear();
            emitter.onNext(true);
            emitter.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        AppManager.getAppManager().finishAllActivity();
                        jumpToActivityAndClearTask(LoginActivity.class);
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {

                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWebView.onPause();
        mWebView.getSettings().setLightTouchEnabled(false);
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.destroy();
        }
        super.onDestroy();
    }

    private void loadWevView() {
        String info = "?id=" + UserCache.getID() +
                "&Authorization=" + UserCache.getAuthorization() +
                "&username=" + UserCache.getUsername() +
                "&name=" + UserCache.getName() +
                "&emailDomain=" + UserCache.getEmailDomain() +
                "&departmentName=" + UserCache.getDepartmentName() +
                "&companyId=" + UserCache.getCompanyId() +
                "&employeeId=" + UserCache.getEmployeeId() +
                "&positionId=" + UserCache.getPositionId() +
                "&departmentId=" + UserCache.getDepartmentId() +
                "&companyName= "+UserCache.getCompanyName()+
                "&companyType=" + UserCache.getCompanyType();
        String s = MyApi.BASE_WEB_URL + innerUrl + info;
        Log.e(TAG, "loadWevView: "+s);
        mWebView.loadUrl(s);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        btnNextRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoading();
                loadWevView();
            }
        });
    }

    /**
     * 软键盘点击事件...
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();//返回上个页面
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && !mWebView.canGoBack()) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
